
#include <cstdio>
#include "GameState/Endgame/Endgame.h"
#include "Engine/Backbone.h"
#include "GameState/DataStorage.h"

namespace GameState {

namespace Endgame {

Endgame::Endgame() : 
	Sense("endGame"),
	Visual("endGame"),
	endgameBg("endgameBg", "screen/endgame"),
	scoreStatusGfx(NULL),
	pieceAverageGfx(NULL),
	totalPiecesGfx(NULL)  {
	/* TODO: make text a resource */
	if(TTF_Init() == -1) {
		printf("TTF_Init: %s\n", TTF_GetError());
		std::exit(2);
	}
	font = TTF_OpenFont("font/maagkramp_by_ficod.ttf", 40);
	if(!font) {
		printf("TTF_OpenFont: %s\n", TTF_GetError());
	}
	pieceCount = 0;
}

Endgame::~Endgame() {
	TTF_CloseFont(font);
	TTF_Quit();
}

// Asks for generation of a graphical model to be displayed
Engine::Resource::GraphicList Endgame::display() {
	Uint16 newGameTime = GameState::DataStorage<Uint16>::get("lastGameTime");
	Uint16 newPieceCount = GameState::DataStorage<Uint16>::get("pieceCount");
	if (newGameTime != gameTime || newPieceCount != pieceCount) {
		if (scoreStatusGfx) delete scoreStatusGfx;
		if (pieceAverageGfx) delete pieceAverageGfx;
		if (totalPiecesGfx) delete totalPiecesGfx;
		gameTime = newGameTime;
		pieceCount = newPieceCount;
		
		SDL_Color color = {255,255,255,0};
		
		char scoreText[255];
		std::sprintf(scoreText, "Game Time - %d seconds", (int)((newGameTime/1000.0)));
		SDL_Surface * gameTimeSurface = TTF_RenderText_Blended(font, scoreText, color);
		scoreStatusGfx = new Engine::Resource::Graphic(gameTimeSurface, scoreText, 2);
		scoreStatusGfx->setCenter(320, 150);

		std::sprintf(scoreText, "Total Pieces - %d", pieceCount);
		SDL_Surface * totalPieesSurface = TTF_RenderText_Blended(font, scoreText, color);
		totalPiecesGfx = new Engine::Resource::Graphic(totalPieesSurface, scoreText, 2);
		totalPiecesGfx->setCenter(320, 200);
		
		std::sprintf(scoreText, "Time per piece - %d seconds", pieceCount != 0 ? (newGameTime/1000)/(pieceCount) : 0);
		SDL_Surface * gameAverageSurface = TTF_RenderText_Blended(font, scoreText, color);
		pieceAverageGfx = new Engine::Resource::Graphic(gameAverageSurface, scoreText, 2);
		pieceAverageGfx->setCenter(320, 250);
	}
	
	
	Engine::Resource::GraphicList gfxList;
	gfxList.push_back(scoreStatusGfx);
	gfxList.push_back(totalPiecesGfx);
	gfxList.push_back(pieceAverageGfx);
	gfxList.push_back(&endgameBg);
	
	return gfxList;
}

void Endgame::keyDown(SDLKey sym, SDLMod mod, Uint16 unicode) {
	if (sym == SDLK_RETURN)	Engine::Backbone::changeContext("masterGameState");
}

void Endgame::setScore(double score, double maxScore)
{
	Endgame::score = score;
	Endgame::maxScore = maxScore;
}

double Endgame::score; 
double Endgame::maxScore; 
Endgame * Endgame::singleInstance = NULL; // Single instance of tutorial screen

} // namespace GameState::Endgame

} // namespace GameState
